<template>
  <div class="svg-icon-wrapper" :style="{
    width: computedSize,
    height: computedSize,
    display: 'inline-flex',
    lineHeight: 0
  }" v-html="processedSvg"></div>
</template>

<script>
export default {
  name: 'SvgIcon',
  props: {
    // SVG文件路径（相对于public目录）
    src: {
      type: String,
      required: true
    },
    // 图标大小
    size: {
      type: [String, Number],
      default: '20px'
    },
    // 图标颜色
    color: {
      type: String,
      default: 'currentColor'
    }
  },
  data() {
    return {
      loadedSvg: ''
    }
  },
  computed: {
    computedSize() {
      if (typeof this.size === 'number') {
        return `${this.size}px`
      }
      return this.size
    },
    processedSvg() {
      if (!this.loadedSvg) return ''

      let processed = this.loadedSvg
        .replace(/<\?xml.*?\?>/, '')
        .replace(/<!DOCTYPE.*?>/, '')
        .trim()

      // 添加或替换fill属性
      if (processed.includes('fill=')) {
        processed = processed.replace(/fill="[^"]+"/g, `fill="${this.color}"`)
      } else {
        processed = processed.replace(/<svg/, `<svg fill="${this.color}"`)
      }

      // 处理尺寸
      processed = processed
        .replace(/width="[^"]+"/, '')
        .replace(/height="[^"]+"/, '')
        .replace(/<svg/, `<svg width="${this.computedSize}" height="${this.computedSize}"`)

      return processed
    }
  },
  watch: {
    src: {
      immediate: true,
      async handler(newSrc) {
        if (newSrc) {
          try {
            // 添加时间戳防止缓存
            const timestamp = new Date().getTime()
            const response = await fetch(`${newSrc}?t=${timestamp}`)
            if (!response.ok) throw new Error('SVG加载失败')
            this.loadedSvg = await response.text()
          } catch (error) {
            console.error('Error loading SVG:', error)
            this.loadedSvg = ''
          }
        }
      }
    }
  }
}
</script>